<template>
  <el-form
    ref="registerFormRef"
    :model="member"
    status-icon
    :rules="registerRules"
    label-width="auto"
    class="demo-ruleForm"
    label-position="left"
  >
    <el-form-item label="电话号" prop="memNumber">
      <el-input v-model="member.memNumber" clearable />
    </el-form-item>
    <el-form-item label="姓名" prop="memName">
      <el-input v-model="member.memName" clearable />
    </el-form-item>
    <el-form-item label="密码" prop="memPwd">
      <el-input v-model="member.memPwd" type="password" autocomplete="off" clearable />
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPwd">
      <el-input v-model="confirmPwd" type="password" autocomplete="off" clearable />
    </el-form-item>
    <el-form-item label="性别" prop="memSex">
      <el-select v-model="member.memSex" placeholder="请选择性别">
        <el-option label="男" value="男" />
        <el-option label="女" value="女" />
      </el-select>
    </el-form-item>
    <el-form-item label="出生日期" prop="memBirthday">
      <el-date-picker
        value-format="YYYY-MM-DD"
        v-model="member.memBirthday"
        type="date"
        placeholder="选择日期"
      />
    </el-form-item>
    <el-form-item label="省市区" prop="province">
      <!-- 省份选择器逻辑应根据实际情况实现 -->
      <grid-cascader style="width: 600px"></grid-cascader>
    </el-form-item>
    <el-form-item label="详细地址" prop="detailedAddress">
      <el-input v-model="member.detailedAddress" type="textarea" rows="2" clearable />
    </el-form-item>
    <el-form-item label="备注" prop="remarks">
      <el-input style="width: 600px" v-model="member.remarks" type="textarea" rows="4" clearable />
    </el-form-item>
  </el-form>
  <div class="form-button" v-if="onShow">
    <el-button style="margin-left: 120px" type="primary" @click="submitRegister(registerFormRef)">
      提交
    </el-button>
    <el-button style="margin-right: 80px" @click="resetForm(registerFormRef)">重置</el-button>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { showErrorMsg } from '@/utils/alterMessage.js'
import { useRegisterStore } from '@/stores/member/register.js'
import { storeToRefs } from 'pinia'
import GridCascader from '@/components/utils/GridCascader.vue'
import { useGridStore } from '@/stores/grid/grid.js'

const gridStore = useGridStore()
const registerStore = useRegisterStore()
const { member, onShow } = storeToRefs(registerStore)
const { gridValue } = storeToRefs(gridStore)

if (!member || !member.value) {
  showErrorMsg('注册页面初始化失败')
}

const registerFormRef = ref(null)
const confirmPwd = ref('')

// 验证规则定义
const validateMemNumber = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else {
    // 假设有效的手机号为11位数字，且以1开头
    // /^1[3-9]\d{9}$/ /^1\d{10}$/
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(value)) {
      callback(new Error('请输入有效的手机号'))
    } else {
      callback()
    }
  }
}
const validateMemName = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入姓名'))
  } else if (!/^[a-zA-Z\u4e00-\u9fa5]+$/.test(value)) {
    // 姓名通常只包含中文或字母
    callback(new Error('姓名只能包含中文或字母'))
  } else {
    callback()
  }
}

const validateMemPwd = (rule, value, callback) => {
  if (!value || value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度至少为6位'))
  } else {
    callback()
  }
}
const validateConfirmPwd = (rule, value, callback) => {
  if (!confirmPwd.value) {
    callback(new Error('请再次输入密码'))
  } else if (confirmPwd.value !== member.value.memPwd) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const validateMemSex = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请选择性别'))
  } else {
    callback()
  }
}

const validateMemBirthday = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请选择出生日期'))
  } else {
    callback()
  }
}

const validateProvince = (rule, value, callback) => {
  if (!gridValue.value || gridValue.value.length === 0) {
    callback(new Error('请选择省市区'))
  } else {
    member.value.province = gridValue.value.join('/')
    callback()
  }
}

const validateDetailedAddress = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入详细地址'))
  } else {
    callback()
  }
}

const validateRemarks = (rule, value, callback) => {
  // 可能不需要验证备注，或者根据需求自定义验证逻辑
  callback()
}

// 完整的验证规则对象
const registerRules = reactive({
  memNumber: [{ validator: validateMemNumber, trigger: 'blur' }],
  memName: [{ validator: validateMemName, trigger: 'blur' }],
  memPwd: [{ validator: validateMemPwd, trigger: 'blur' }],
  confirmPwd: [{ validator: validateConfirmPwd, trigger: 'blur' }],
  memSex: [{ validator: validateMemSex, trigger: 'change' }],
  memBirthday: [{ validator: validateMemBirthday, trigger: 'change' }],
  province: [{ validator: validateProvince, trigger: 'change' }],
  detailedAddress: [{ validator: validateDetailedAddress, trigger: 'blur' }],
  remarks: [{ validator: validateRemarks, trigger: 'blur' }]
})

const submitRegister = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        //用户地址处理
        registerStore.addAddress()
        // await memberStore.register(member)
        // 注册成功后的处理逻辑
        await registerStore.register()
      } catch (error) {
        showErrorMsg('注册失败，请检查输入信息')
      }
    } else {
      showErrorMsg('请按要求填写所有必填项')
    }
  })
}

// 在表单组件的<script setup>部分添加以下代码
const validateForm = (callback) => {
  if (registerFormRef.value) {
    registerFormRef.value.validate((valid) => {
      if (valid) {
        callback(true) // 表单验证通过，执行回调
      } else {
        callback(false) // 表单验证未通过
      }
    })
  }
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

defineExpose({
  validateForm
})
</script>

<style lang="scss" scoped>
.demo-ruleForm {
  display: grid;
  grid-template-columns: repeat(2, 1fr); //设置两列布局
  /* 调整列间距为30px */
  column-gap: 40px;
  /* 调整行间距为20px */
  row-gap: 20px;
  // 添加新的Grid区域规则，使备注控件独占一行
  & > :nth-child(n + 7) {
    // 假设备注控件是第8个表单项开始
    grid-column: 1 / span 2; // 让该元素跨越两列
  }
}

.form-button {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  margin-bottom: 50px;
}
</style>
